package cn.cloud.all.security.web.header.writers;

import cn.cloud.all.security.web.header.Header;
import cn.cloud.all.security.web.header.HeaderWriter;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

public class StaticHeadersWriter implements HeaderWriter {

    private final List<Header> headers;

    public StaticHeadersWriter(List<Header> headers) {
        Assert.notEmpty(headers, "headers cannot be null or empty");
        this.headers = headers;
    }

    public StaticHeadersWriter(String headerName, String... headerValues) {
        this(Collections.singletonList(new Header(headerName, headerValues)));
    }

    public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
        for (Header header : headers) {
            if (!response.containsHeader(header.getName())) {
                for (String value : header.getValues()) {
                    response.addHeader(header.getName(), value);
                }
            }
        }
    }

    @Override
    public String toString() {
        return getClass().getName() + " [headers=" + headers + "]";
    }
}
